#include "interpolator.h"
#include <math.h>
#include <stdlib.h>

Interpolator::Interpolator(double yCol[], double xCol[], DWORD n)
{
	m_pyCol = yCol;
	m_pxCol = xCol;
	m_n = n;

	m_xlocator = new Locator(m_pxCol, n);
	int firstSeg = m_xlocator->Seg();
	_MakeLine(firstSeg);
}

Interpolator::~Interpolator()
{
	delete m_xlocator;
}

void Interpolator::_MakeLine(DWORD iSeg)
{
	double x1, y1, x2, y2;
	if (m_n == 1 || m_xlocator->InZeroSide()) {
		x1 = 0.0;
		y1 = 0.0;
		if (m_xlocator->Seg() == 0) {
			x2 = m_pxCol[0];
			y2 = m_pyCol[0];
		}
		else {
			x2 = m_pxCol[m_n-1];
			y2 = m_pyCol[m_n-1];
		}
	}
	else {
		iSeg = __max(iSeg, 1);
		iSeg = __min(iSeg, m_n-1);
		x1 = m_pxCol[iSeg-1];
		y1 = m_pyCol[iSeg-1];
		x2 = m_pxCol[iSeg];
		y2 = m_pyCol[iSeg];
	}

	m_k = (y2 - y1) / (x2 - x1);
	m_b = y1 - m_k * x1;
}

double Interpolator::At(double x)
{
	DWORD iNextSeg = m_xlocator->At(x);
	if(m_xlocator->IsMoved()) {
		_MakeLine(iNextSeg);
	}
	double y = m_k * x + m_b;
	return(y);
}

void Interpolator::Reset(void)
{
	DWORD segAt0 = m_xlocator->At(0.0);
	_MakeLine(segAt0);
}
